<template>
    <div class="user-list-container">
        <h1>用户信息管理</h1>

        <!-- 用户搜索和筛选区域 -->
        <div class="user-filters">
            <el-input v-model="searchKeyword" placeholder="请输入用户名或邮箱" style="width: 300px; margin-right: 20px;"
                clearable @keyup.enter="fetchUsers" />
            <el-button type="primary" @click="fetchUsers">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="showCreateUserDialog" style="float: right;">新增用户</el-button>
        </div>

        <!-- 用户列表表格 -->
        <el-table :data="users" v-loading="loading" style="width: 100%; margin-top: 20px;" border>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="用户名" width="150" />
            <el-table-column prop="email" label="邮箱" width="200" />
            <el-table-column prop="role" label="角色" width="120">
                <template #default="scope">
                    <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'info'">
                        {{ scope.row.role }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 'active' ? 'success' : 'warning'">
                        {{ scope.row.status === 'active' ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" fixed="right" width="200">
                <template #default="scope">
                    <el-button size="small" @click="viewUser(scope.row)">查看</el-button>
                    <el-button size="small" type="primary" @click="editUser(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteUser(scope.row)"
                        :disabled="scope.row.role === 'admin'">
                        删除
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="200">    
                <template #default="scope">
                    <el-button size="small" @click="viewUser(scope.row)">查看</el-button>
                    <el-button size="small" type="primary" @click="editUser(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteUser(scope.row)"
                        :disabled="scope.row.role === 'admin'"></el-button>
                </template>
            </el-table-column>
                 <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" @submit.prevent="submitForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" native-type="submit">
                        登录
                    </el-button>
                </el-form-item>
                <!-- <el-form-item label="图片" prop="img">
                    <el-upload name="img" action="https://jsonplaceholder.typicode.com/posts/" :on-success="uploadImg"
                        :file-list="[]" :before-upload="validateImg">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div style="margin-top: 10px"></div>
                        </el-upload>
                </el-form-item> -->
                上传图片
                <el-form-item label="图片" prop="img">
                    <el-upload name="img" action="https://jsonplaceholder.typicode.com/posts/" :on-success="uploadImg"
                        :file-list="[]" :before-upload="validateImg">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div style="margin-top: 10px">
                            <el-tooltip content="只能上传图片格式文件" placement="top">
                                <el-icon type="question-circle-o"></el-icon>
                            </el-tooltip>
                        </div>
                    </el-upload>
                </el-form-item>
                
                <!-- <el-button type="text" @click="toggleForm"> 
                    去注册
                </el-button> -->
            </el-form>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; text-align: right;" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />

        <!-- 用户详情对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
            <el-form :model="currentUser" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="currentUser.name" :disabled="!isEdit"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="currentUser.email" :disabled="!isEdit"></el-input>
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="currentUser.role" :disabled="!isEdit" style="width: 100%;">
                        <el-option label="普通用户" value="user"></el-option>
                        <el-option label="管理员" value="admin"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="currentUser.status" active-value="active" inactive-value="inactive"
                        :disabled="!isEdit" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button v-if="isEdit" type="primary" @click="saveUser">保存</el-button>
                        <el-button v-else type="primary" @click="createUser">创建</el-button>
                     <el-button v-else type="primary" @click="updateUser">更新</el-button>
                </span>
                
            </template>
        
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 用户数据
const users = ref([])
const loading = ref(false)

// 搜索关键词
const searchKeyword = ref('')

// 分页信息
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentUser = ref({
    id: null,
    name: '',
    email: '',
    role: 'user',
    status: 'active',
    createTime: ''
})

// 获取用户列表
const fetchUsers = async () => {
    loading.value = true
    try {
        // 这里应该调用实际的API接口
        // 模拟数据
        const mockData = [
            { id: 1, name: '张三', email: 'zhangsan@example.com', role: 'admin', status: 'active', createTime: '2023-01-15' },
            { id: 2, name: '李四', email: 'lisi@example.com', role: 'user', status: 'active', createTime: '2023-02-20' },
            { id: 3, name: '王五', email: 'wangwu@example.com', role: 'user', status: 'inactive', createTime: '2023-03-10' }
        ]

        users.value = mockData
        pagination.value.total = mockData.length
    } catch (error) {
        ElMessage.error('获取用户列表失败')
    } finally {
        loading.value = false
    }
}

        // 时间戳格式化
        const getCurrentTime = () => {
            const date = new Date();
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const hours = date.getHours();
            const minutes = date.getMinutes();
            const seconds = date.getSeconds();
            const time = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return time;
        };
        // 登录
        const login = (username, password) => {
            const time = getCurrentTime();
            console.log(`登录时间: ${time}`);
            console.log(`用户名: ${username}`);
            console.log(`密码: ${password}`);
            return true;
        };
// 重置搜索
const resetSearch = () => {
    searchKeyword.value = ''
    fetchUsers()
}

onMounted(() => {
    fetchUsers()
})
// 创建用户
const createUser = () => {
    currentUser.value = {
        id: null,
        name: '',
        email: '',
        role: 'user',
        status: 'active',
        createTime: ''
    }
    dialogTitle.value = '新增用户'
    isEdit.value = true
    dialogVisible.value = true
}

// 更新用户
const updateUser = () => {
    // 这里应该调用实际的API接口
    ElMessage.success('更新成功')
    dialogVisible.value = false
    fetchUsers()
}

    
// 查看用户详情
const viewUser = (user) => {
    currentUser.value = { ...user }
    dialogTitle.value = '用户详情'
    isEdit.value = false
    dialogVisible.value = true
}

// 编辑用户
const editUser = (user) => {
    currentUser.value = { ...user }
    dialogTitle.value = '编辑用户'
    isEdit.value = true
    dialogVisible.value = true
}

// 新增用户
const showCreateUserDialog = () => {
    currentUser.value = {
        id: null,
        name: '',
        email: '',
        role: 'user',
        status: 'active',
        createTime: ''
    }
    dialogTitle.value = '新增用户'
    isEdit.value = true
    dialogVisible.value = true
}

// 保存用户（新增或修改）
const saveUser = () => {
    // 这里应该调用实际的API接口
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchUsers()
}

// 删除用户
const deleteUser = (user) => {
    ElMessageBox.confirm(
        `确定要删除用户 ${user.name} 吗？`,
        '确认删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        // 这里应该调用实际的API接口
        ElMessage.success('删除成功')
        fetchUsers()
    }).catch(() => {
        // 取消删除
    })
}

// 分页相关方法
const handleSizeChange = (val) => {
    pagination.value.pageSize = val
    fetchUsers()
}

const handleCurrentChange = (val) => {
    pagination.value.currentPage = val
    fetchUsers()
}

// 组件挂载时获取数据
onMounted(() => {
    fetchUsers()
})
</script>

<style scoped>
.user-list-container {
    padding: 20px;
    background-color: #fff;
}

.user-filters {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.dialog-footer {
    text-align: right;
}
</style>